package com.java.jdbc;

import java.sql.*;
import java.util.Scanner;

/**
 * 登录案例
 */
public class LoginDemo {

    public static final String URL = "jdbc:mysql://localhost:3306/mydb?serverTimezone=GMT";
    public static final String USER = "root";
    public static final String PASSWORD = "123456";

    /**
     * 登录方法(存在SQL注入问题）
     */
    public static boolean login(String username,String password){
        //通过驱动管理获得数据库连接
        try(Connection connection = DriverManager.getConnection(URL, USER, PASSWORD)){
            //获得编译命令对象
            Statement statement = connection.createStatement();
            //执行查询命令
            String sql = "select * from t_user where username = '"+ username + "' and password = '" + password + "'";
            System.out.println(sql);
            ResultSet resultSet = statement.executeQuery(sql);
            //判断结果集是否为空，不为空则登录成功
            if(resultSet.next()){
                return true;
            }
        }catch (Exception e){
            e.printStackTrace();
        }
        return false;
    }

    /**
     * 登录方法
     */
    public static boolean login2(String username,String password){
        //通过驱动管理获得数据库连接
        try(Connection connection = DriverManager.getConnection(URL, USER, PASSWORD)){
            //获得编译命令对象
            PreparedStatement statement = connection.prepareStatement("select * from t_user where username = ? and password = ?");
            //执行查询命令
            statement.setString(1,username);
            statement.setString(2,password);
            ResultSet resultSet = statement.executeQuery();
            //判断结果集是否为空，不为空则登录成功
            if(resultSet.next()){
                return true;
            }
        }catch (Exception e){
            e.printStackTrace();
        }
        return false;
    }

    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
        System.out.println("请输入账号：");
        String username = scanner.nextLine();
        System.out.println("请输入密码：");
        String password = scanner.nextLine();
        if(login2(username,password)){
            System.out.println("登录成功");
        }else{
            System.out.println("登录失败");
        }
    }
}
